package com.tencent.cloud.iov.kernel.util;

import android.util.Pair;

import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.tencent.cloud.iov.kernel.IovKernel;
import com.tencent.cloud.iov.kernel.service.exception.ServerException;
import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.util.NetworkUtils;

import org.json.JSONException;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import retrofit2.HttpException;

/**
 * @author vinsonhuang
 * @date 2018/6/8
 */
public class ExceptionUtils {

    private static final String TAG = ExceptionUtils.class.getSimpleName();

    /**
     * 处理异常：将异常转换为相应的错误码
     * <p>
     * 先判断网络是否可用，在处理异常;
     * 异常处理顺序：UnknownHostException -> SocketException -> SocketTimeoutException -> IOException
     *
     * @param throwable
     * @return pair[first:code, second:msg]
     */
    public static Pair<Integer, String> handleThrowable(Throwable throwable) {
        int code;
        String msg;

        // 先判断网络是否可用
        if (!NetworkUtils.isNetworkAvailable(IovKernel.getContext())) {
            code = StatusCode.NETWORK_ERROR;
            msg = StatusCode.MSG_NETWORK_ERROR;
            return new Pair<>(code, msg);
        }

        // 若网络可用，再判断异常
        if (throwable instanceof UnknownHostException) {
            code = StatusCode.UNKNOWN_HOST_ERROR;
            msg = StatusCode.MSG_UNKNOWN_HOST_ERROR;
        } else if (throwable instanceof SSLHandshakeException) {
            code = StatusCode.NETWORK_ERROR;
            msg = StatusCode.MSG_NETWORK_ERROR;
        } else if (throwable instanceof ConnectException
                || throwable instanceof SocketException
                || throwable instanceof SocketTimeoutException) {
            code = StatusCode.CONNECT_ERROR;
            msg = StatusCode.MSG_CONNECT_ERROR;
        } else if (throwable instanceof IOException) {
            code = StatusCode.HTTP_ERROR;
            msg = StatusCode.MSG_HTTP_ERROR;
        } else if (throwable instanceof HttpException) {
            code = StatusCode.HTTP_ERROR;
            msg = StatusCode.MSG_HTTP_ERROR;
        } else if (throwable instanceof JsonParseException
                || throwable instanceof JSONException
                || throwable instanceof JsonSyntaxException) {
            code = StatusCode.JSON_PARSE_ERROR;
            msg = StatusCode.MSG_JSON_PARSE_ERROR;
        } else if (throwable instanceof ServerException) {
            code = StatusCode.SERVER_INTERNAL_ERROR;
            msg = StatusCode.MSG_SERVER_INTERNAL_ERROR;
        } else {
            code = StatusCode.UNKNOWN_ERROR;
            msg = StatusCode.MSG_UNKNOWN_ERROR;
        }
        return new Pair<>(code, msg);
    }
}
